import { Component, OnInit } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { HttpClient, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { SharedModule } from '../../shared/shared.module';
import { Router, RouterModule } from '@angular/router';
import { PagedResultDto } from '@abp/ng.core';

// 批次查询数据接口
interface ChaKanGuanLianDto {
  id: number;
  serialNumber: number;
  goodsCode: string;
  goodsName: string;
  goodsType: string;
  specification: string;
  unit: string;
  batchNumber: string;
  currentStock: number;
  productionDate: string;
  expiryDate: string;
  warehouseName: string;
  locationName: string;
  status: string;
  remark: string;
}

// 查询参数接口
interface QueryParams {
  GoodsCodeOrName?: string;
  GoodsType?: string;
  BatchNumber?: string;
  WarehouseName?: string;
  ProductionDateStart?: string;
  ProductionDateEnd?: string;
  ExpiryDateStart?: string;
  ExpiryDateEnd?: string;
  Unit?: string;
  SkipCount: number;
  MaxResultCount: number;
  Sorting?: string;
}

@Component({
  selector: 'app-pi-ci-cha-xun',
  standalone: true,
  imports: [
    CommonModule,
    FormsModule,
    SharedModule,
    RouterModule
  ],
  templateUrl: './pi-ci-cha-xun.component.html',
  styleUrls: ['./pi-ci-cha-xun.component.scss']
})
export class PiCiChaXunComponent implements OnInit {
  // 使Math可在模板中访问
  Math = Math;
  // 使Array可在模板中访问
  Array = Array;
  // 使console可在模板中访问
  console = console;
  
  // 查询参数
  queryParams: QueryParams = {
    SkipCount: 0,
    MaxResultCount: 10,
    Sorting: ''
  };

  // 页码和页大小设置
  pageIndex = 1;
  pageSize = 10;
  total = 0;
  pageSizeOptions = [10, 20, 30, 50];
  inputPageNumber = 1;
  
  // 最大页数
  get maxPageCount(): number {
    return Math.ceil(this.total / this.pageSize) || 1;
  }

  // 批次数据
  dataList: ChaKanGuanLianDto[] = [];
  allDataList: ChaKanGuanLianDto[] = []; // 用于存储所有数据，提取下拉选项
  
  // 下拉选项 - 会在从数据中提取
  goodsTypeOptions: string[] = [];
  warehouseOptions: string[] = [];
  statusOptions: string[] = ['正常', '即将过期', '已过期'];
  
  loading = false;
  apiError = false;
  errorMessage = '';
  
  // 日期筛选默认值
  defaultStartDate = new Date();
  defaultEndDate = new Date();

  constructor(
    private http: HttpClient,
    private router: Router
  ) {
    // 设置默认开始日期为30天前
    this.defaultStartDate = new Date();
    this.defaultStartDate.setDate(this.defaultStartDate.getDate() - 30);
    
    // 设置默认结束日期为当前日期
    this.defaultEndDate = new Date();
    
    // 不再设置默认日期筛选，默认为空
    // this.queryParams.ProductionDateStart = this.formatDate(this.defaultStartDate);
    // this.queryParams.ProductionDateEnd = this.formatDate(this.defaultEndDate);
  }

  ngOnInit(): void {
    // 尝试从服务器获取下拉选项
    this.fetchOptionsFromServer();
    // 加载数据
    this.loadData();
  }
  
  // 从服务器获取下拉选项
  fetchOptionsFromServer(): void {
    console.log('尝试从服务器获取下拉选项...');
    
    // 创建一个包含大量数据的请求，以获取更多数据用于提取选项
    const apiUrl = 'https://localhost:44359/api/app/cha-kan-guan-lian';
    let params = new HttpParams()
      .set('MaxResultCount', '1000') // 获取尽可能多的数据
      .set('SkipCount', '0');
    
    this.http.get<PagedResultDto<ChaKanGuanLianDto>>(apiUrl, { params })
      .subscribe({
        next: (response) => {
          if (response && response.items && response.items.length > 0) {
            console.log('成功获取选项数据，记录数:', response.items.length);
            // 更新全部数据列表
            this.updateAllDataList(response.items);
            // 从数据中提取下拉选项
            this.extractOptionsFromData();
          } else {
            console.warn('获取选项数据为空，将使用模拟数据');
            // 创建模拟数据并提取选项
            this.createMockOptionsData();
          }
        },
        error: (error) => {
          console.error('获取选项数据失败:', error);
          // 创建模拟数据并提取选项
          this.createMockOptionsData();
        }
      });
  }
  
  // 更新全部数据列表
  updateAllDataList(newData: ChaKanGuanLianDto[]): void {
    // 合并新数据到全部数据列表，避免重复
    newData.forEach(item => {
      const exists = this.allDataList.some(existingItem => existingItem.id === item.id);
      if (!exists) {
        this.allDataList.push(item);
      }
    });
  }
  
  // 从数据中提取下拉选项
  extractOptionsFromData(): void {
    // 货品类型选项（去重）
    const goodsTypeSet = new Set<string>();
    this.allDataList.forEach(item => {
      if (item.goodsType && item.goodsType.trim() !== '') goodsTypeSet.add(item.goodsType);
    });
    this.goodsTypeOptions = Array.from(goodsTypeSet).sort();
    
    // 仓库名称选项（去重）
    const warehouseSet = new Set<string>();
    this.allDataList.forEach(item => {
      if (item.warehouseName && item.warehouseName.trim() !== '') warehouseSet.add(item.warehouseName);
    });
    this.warehouseOptions = Array.from(warehouseSet).sort();
    
    console.log('从数据中提取的货品类型选项:', this.goodsTypeOptions);
    console.log('从数据中提取的仓库选项:', this.warehouseOptions);
    
    // 如果选项为空，添加一些默认选项
    if (this.goodsTypeOptions.length === 0) {
      this.goodsTypeOptions = ['电子产品', '家电', '食品', '服装', '化妆品', '办公用品'];
      console.warn('未能从数据中提取货品类型选项，使用默认值');
    }
    
    if (this.warehouseOptions.length === 0) {
      this.warehouseOptions = ['北京仓', '上海仓', '广州仓', '成都仓'];
      console.warn('未能从数据中提取仓库选项，使用默认值');
    }
  }
  
  // 创建模拟数据用于提取选项
  createMockOptionsData(): void {
    console.log('创建模拟数据用于提取下拉选项...');
    
    // 生成足够多样化的模拟数据以提供丰富的选项
    const mockItems: ChaKanGuanLianDto[] = [];
    
    // 模拟数据中的货品类型
    const goodsTypes = ['电子产品', '家电', '食品', '服装', '化妆品', '办公用品', '日用品', '医药用品', '文具', '工具'];
    
    // 模拟数据中的仓库名称
    const warehouses = ['北京仓', '上海仓', '广州仓', '成都仓', '武汉仓', '西安仓', 'A区-01', 'B区-02', 'C区-03'];
    
    // 生成30条模拟数据以确保覆盖各种情况
    for (let i = 1; i <= 30; i++) {
      const productionDate = new Date();
      productionDate.setDate(productionDate.getDate() - 180 - i * 5);
      
      const expiryDate = new Date(productionDate);
      expiryDate.setFullYear(expiryDate.getFullYear() + 1);
      
      const mockItem: ChaKanGuanLianDto = {
        id: i,
        serialNumber: i,
        goodsCode: `G${String(i).padStart(5, '0')}`,
        goodsName: `测试商品${i}`,
        goodsType: goodsTypes[i % goodsTypes.length],
        specification: `型号${i}`,
        unit: i % 2 === 0 ? '个' : '箱',
        batchNumber: `BT${String(i).padStart(5, '0')}`,
        currentStock: 100 + i * 10,
        productionDate: this.formatDate(productionDate),
        expiryDate: this.formatDate(expiryDate),
        warehouseName: warehouses[i % warehouses.length],
        locationName: `货架${String.fromCharCode(65 + (i % 5))}-${i % 10}`,
        status: this.getStatus(this.formatDate(expiryDate)),
        remark: `备注信息${i}`
      };
      
      mockItems.push(mockItem);
    }
    
    // 更新全部数据列表
    this.updateAllDataList(mockItems);
    
    // 从数据中提取下拉选项
    this.extractOptionsFromData();
  }
  
  // 格式化日期为YYYY-MM-DD
  formatDate(date: Date): string {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
  }
  
  // 计算剩余天数
  calculateRemainingDays(expiryDate: string): number {
    if (!expiryDate) return 0;
    
    const expDate = new Date(expiryDate);
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 重置时间为当天开始
    
    const diffTime = expDate.getTime() - today.getTime();
    return Math.ceil(diffTime / (1000 * 60 * 60 * 24));
  }
  
  // 获取状态
  getStatus(expiryDate: string): string {
    const remainingDays = this.calculateRemainingDays(expiryDate);
    if (remainingDays > 30) return '正常';
    if (remainingDays >= 0) return '即将过期';
    return '已过期';
  }

  // 重置筛选条件
  reset(): void {
    // 保存当前页大小
    const currentPageSize = this.pageSize;
    
    // 完全重置查询参数
    this.queryParams = {
      SkipCount: 0,
      MaxResultCount: currentPageSize,
      Sorting: ''
    };
    
    // 重置页码
    this.pageIndex = 1;
    
    // 重新加载数据
    this.loadData();
  }

  // 加载数据
  loadData(): void {
    console.log('开始加载数据，当前页码:', this.pageIndex, '页大小:', this.pageSize);
    console.log('当前查询参数:', JSON.stringify(this.queryParams));
    
    // 调试日期参数
    if (this.queryParams.ProductionDateStart || this.queryParams.ProductionDateEnd || 
        this.queryParams.ExpiryDateStart || this.queryParams.ExpiryDateEnd) {
      console.log('日期筛选条件:');
      console.log('- 生产日期开始:', this.queryParams.ProductionDateStart || '无');
      console.log('- 生产日期结束:', this.queryParams.ProductionDateEnd || '无');
      console.log('- 到期日期开始:', this.queryParams.ExpiryDateStart || '无');
      console.log('- 到期日期结束:', this.queryParams.ExpiryDateEnd || '无');
    }
    
    this.loading = true;
    this.apiError = false;
    
    this.queryParams.SkipCount = (this.pageIndex - 1) * this.pageSize;
    this.queryParams.MaxResultCount = this.pageSize;
    
    const apiUrl = 'https://localhost:44359/api/app/cha-kan-guan-lian';
    
    // 创建HttpParams对象
    let params = new HttpParams();
    
    // 添加查询参数
    Object.keys(this.queryParams).forEach(key => {
      const value = this.queryParams[key as keyof QueryParams];
      if (value !== undefined && value !== null && value !== '') {
        params = params.set(key, String(value));
      }
    });
    
    console.log('发送请求参数:', params.toString());
    
    this.http.get<PagedResultDto<ChaKanGuanLianDto>>(apiUrl, { params })
      .subscribe({
        next: (response) => {
          console.log('API返回数据:', response);
          if (response && response.items) {
            this.dataList = response.items.map(item => {
              return {
                ...item,
                status: this.getStatus(item.expiryDate)
              };
            });
            this.total = response.totalCount;
            
            // 更新全部数据列表，用于提取下拉选项
            this.updateAllDataList(response.items);
            // 从数据中提取下拉选项
            this.extractOptionsFromData();
          }
          this.loading = false;
          console.log('数据加载完成，当前dataList长度:', this.dataList.length);
        },
        error: (error: HttpErrorResponse) => {
          console.error('获取批次数据失败:', error);
          this.loading = false;
          this.apiError = true;
          
          if (error.status === 0) {
            this.errorMessage = '网络错误或CORS问题，请检查网络连接和后端CORS配置';
          } else {
            this.errorMessage = `获取数据失败: ${error.status} ${error.statusText}`;
            if (error.error && error.error.error) {
              this.errorMessage += ` - ${error.error.error.message || '未知错误'}`;
            }
          }
          
          // 使用模拟数据
          this.mockData();
        }
      });
  }
  
  // 模拟数据
  mockData(): void {
    // 设置总数据量
    this.total = 100; // 假设总共有100条数据
    
    // 清空现有数据
    this.dataList = [];
    
    const mockItems: ChaKanGuanLianDto[] = [];
    
    // 生成模拟数据，确保每页数据不同
    const startIndex = (this.pageIndex - 1) * this.pageSize;
    const endIndex = Math.min(startIndex + this.pageSize - 1, this.total - 1);
    
    console.log('生成模拟数据，范围:', startIndex, '至', endIndex);
    
    for (let i = startIndex; i <= endIndex; i++) {
      // 使用i作为种子生成固定的随机数，确保同一条记录的数据一致性
      const seed = i * 12345;
      const randomValue = ((seed * 9301 + 49297) % 233280) / 233280;
      
      const productionDate = new Date();
      productionDate.setDate(productionDate.getDate() - 180 - i * 5); // 生产日期在6个月前，每条记录相差5天
      
      const expiryDate = new Date(productionDate);
      expiryDate.setFullYear(expiryDate.getFullYear() + 1); // 过期日期为生产日期后一年
      
      // 使用固定种子生成货品编码，确保同一条记录的编码一致
      const goodsCode = `HPDH${String(Math.floor(randomValue * 10000)).padStart(4, '0')}`;
      
      const mockItem: ChaKanGuanLianDto = {
        id: i,
        serialNumber: i,
        goodsCode: goodsCode,
        goodsName: `测试商品${i}`,
        goodsType: this.goodsTypeOptions[i % this.goodsTypeOptions.length],
        specification: `规格${i}`,
        unit: '个',
        batchNumber: `BT${String(2025070700 + i)}`,
        currentStock: 50 + i * 10,
        productionDate: this.formatDate(productionDate),
        expiryDate: this.formatDate(expiryDate),
        warehouseName: this.warehouseOptions[i % this.warehouseOptions.length],
        locationName: `${String.fromCharCode(65 + (i % 5))}区`,
        status: this.getStatus(this.formatDate(expiryDate)),
        remark: `批次${i}备注信息`
      };
      
      // 应用日期过滤条件
      let matchesDateFilter = true;
      
      // 检查生产日期筛选
      if (this.queryParams.ProductionDateStart || this.queryParams.ProductionDateEnd) {
        const itemDate = new Date(mockItem.productionDate);
        
        // 检查开始日期
        if (this.queryParams.ProductionDateStart) {
          const filterStart = new Date(this.queryParams.ProductionDateStart);
          filterStart.setHours(0, 0, 0, 0);
          if (itemDate < filterStart) {
            matchesDateFilter = false;
          }
        }
        
        // 检查结束日期
        if (this.queryParams.ProductionDateEnd && matchesDateFilter) {
          const filterEnd = new Date(this.queryParams.ProductionDateEnd);
          filterEnd.setHours(23, 59, 59, 999);
          if (itemDate > filterEnd) {
            matchesDateFilter = false;
          }
        }
      }
      
      // 检查过期日期筛选
      if ((this.queryParams.ExpiryDateStart || this.queryParams.ExpiryDateEnd) && matchesDateFilter) {
        const itemDate = new Date(mockItem.expiryDate);
        
        // 检查开始日期
        if (this.queryParams.ExpiryDateStart) {
          const filterStart = new Date(this.queryParams.ExpiryDateStart);
          filterStart.setHours(0, 0, 0, 0);
          if (itemDate < filterStart) {
            matchesDateFilter = false;
          }
        }
        
        // 检查结束日期
        if (this.queryParams.ExpiryDateEnd) {
          const filterEnd = new Date(this.queryParams.ExpiryDateEnd);
          filterEnd.setHours(23, 59, 59, 999);
          if (itemDate > filterEnd) {
            matchesDateFilter = false;
          }
        }
      }
      
      // 检查货品类型筛选
      let matchesTypeFilter = true;
      if (this.queryParams.GoodsType && mockItem.goodsType !== this.queryParams.GoodsType) {
        matchesTypeFilter = false;
      }
      
      // 检查仓库名称筛选
      let matchesWarehouseFilter = true;
      if (this.queryParams.WarehouseName && mockItem.warehouseName !== this.queryParams.WarehouseName) {
        matchesWarehouseFilter = false;
      }
      
      // 只有符合所有条件的数据才添加到结果中
      if (matchesDateFilter && matchesTypeFilter && matchesWarehouseFilter) {
        mockItems.push(mockItem);
      }
    }
    
    // 日期筛选可能导致数据量减少，需要补足数据
    if (mockItems.length < this.pageSize && endIndex < 99) {
      let additionalCount = this.pageSize - mockItems.length;
      let additionalIndex = endIndex + 1;
      
      while (additionalCount > 0 && additionalIndex < 100) {
        const seed = additionalIndex * 12345;
        const randomValue = ((seed * 9301 + 49297) % 233280) / 233280;
        
        const productionDate = new Date();
        productionDate.setDate(productionDate.getDate() - 180 - additionalIndex * 5);
        
        const expiryDate = new Date(productionDate);
        expiryDate.setFullYear(expiryDate.getFullYear() + 1);
        
        const goodsCode = `HPDH${String(Math.floor(randomValue * 10000)).padStart(4, '0')}`;
        
        // 根据筛选条件调整生成的数据，确保符合条件
        const adjustedProductionDate = this.queryParams.ProductionDateStart 
          ? new Date(this.queryParams.ProductionDateStart) 
          : productionDate;
        
        const adjustedExpiryDate = this.queryParams.ExpiryDateStart 
          ? new Date(this.queryParams.ExpiryDateStart) 
          : expiryDate;
          
        // 如果有结束日期限制，在范围内随机生成日期
        if (this.queryParams.ProductionDateEnd) {
          const prodEndDate = new Date(this.queryParams.ProductionDateEnd);
          if (adjustedProductionDate < prodEndDate) {
            // 在开始和结束日期之间随机选择一个日期
            const timeDiff = prodEndDate.getTime() - adjustedProductionDate.getTime();
            const randomOffset = Math.floor(randomValue * timeDiff);
            adjustedProductionDate.setTime(adjustedProductionDate.getTime() + randomOffset);
          }
        }
        
        if (this.queryParams.ExpiryDateEnd) {
          const expEndDate = new Date(this.queryParams.ExpiryDateEnd);
          if (adjustedExpiryDate < expEndDate) {
            // 在开始和结束日期之间随机选择一个日期
            const timeDiff = expEndDate.getTime() - adjustedExpiryDate.getTime();
            const randomOffset = Math.floor(randomValue * timeDiff);
            adjustedExpiryDate.setTime(adjustedExpiryDate.getTime() + randomOffset);
          }
        }
          
        // 确保过期日期在生产日期之后
        if (adjustedExpiryDate <= adjustedProductionDate) {
          adjustedExpiryDate.setFullYear(adjustedProductionDate.getFullYear() + 1);
        }
        
        const mockItem: ChaKanGuanLianDto = {
          id: additionalIndex,
          serialNumber: additionalIndex,
          goodsCode: goodsCode,
          goodsName: `测试商品${additionalIndex}`,
          goodsType: this.queryParams.GoodsType || this.goodsTypeOptions[additionalIndex % this.goodsTypeOptions.length],
          specification: `规格${additionalIndex}`,
          unit: '个',
          batchNumber: `BT${String(2025070700 + additionalIndex)}`,
          currentStock: 50 + additionalIndex * 10,
          productionDate: this.formatDate(adjustedProductionDate),
          expiryDate: this.formatDate(adjustedExpiryDate),
          warehouseName: this.queryParams.WarehouseName || this.warehouseOptions[additionalIndex % this.warehouseOptions.length],
          locationName: `${String.fromCharCode(65 + (additionalIndex % 5))}区`,
          status: this.getStatus(this.formatDate(adjustedExpiryDate)),
          remark: `批次${additionalIndex}备注信息`
        };
        
        mockItems.push(mockItem);
        additionalCount--;
        additionalIndex++;
      }
    }
    
    // 直接赋值，不要追加
    this.dataList = mockItems;
    
    // 更新总数量 - 如果有筛选条件，总数可能会减少
    if (this.queryParams.ProductionDateStart || this.queryParams.ExpiryDateStart || 
        this.queryParams.GoodsType || this.queryParams.WarehouseName) {
      // 假设筛选后的总数为当前页数量的5倍
      this.total = Math.min(mockItems.length * 5, 100);
    }
    
    console.log('模拟数据生成完成，条数:', mockItems.length);
  }

  // 页码变更
  pageIndexChange(index: number): void {
    console.log('页码变更，从', this.pageIndex, '变为', index);
    if (index < 1 || index > this.maxPageCount) {
      return;
    }
    this.pageIndex = index;
    this.inputPageNumber = index;
    
    // 先清空数据列表，避免显示旧数据
    this.dataList = [];
    
    // 加载新页面数据
    this.loadData();
  }

  // 获取当前应该显示的页码数组
  getPageNumbers(): number[] {
    const maxPage = this.maxPageCount;
    const currentPage = this.pageIndex;
    
    if (maxPage <= 5) {
      // 总页数小于等于5，显示所有页码
      return Array.from({length: maxPage}, (_, i) => i + 1);
    } else if (currentPage <= 3) {
      // 当前页在前3页
      return [1, 2, 3, 4, 5];
    } else if (currentPage >= maxPage - 2) {
      // 当前页在后3页
      return [maxPage - 4, maxPage - 3, maxPage - 2, maxPage - 1, maxPage];
    } else {
      // 当前页在中间
      return [currentPage - 2, currentPage - 1, currentPage, currentPage + 1, currentPage + 2];
    }
  }

  // 页大小变更
  pageSizeChange(size: number): void {
    this.pageSize = Number(size);
    this.pageIndex = 1;
    this.loadData();
  }
  
  // 处理页码输入变化
  onPageInputChange(event: any): void {
    let page = parseInt(event.target.value);
    if (isNaN(page)) {
      page = 1;
    }
    if (page < 1) {
      page = 1;
    }
    if (page > this.maxPageCount) {
      page = this.maxPageCount;
    }
    this.inputPageNumber = page;
  }
  
  // 处理页码输入回车
  onPageInputKeyUp(event: KeyboardEvent): void {
    if (event.key === 'Enter') {
      this.goToPage(this.inputPageNumber);
    }
  }
  
  // 跳转到指定页
  goToPage(page: number): void {
    this.pageIndexChange(page);
  }

  // 搜索
  search(): void {
    console.log('执行搜索，查询参数:', this.queryParams);
    
    // 确保日期格式正确
    if (this.queryParams.ProductionDateStart) {
      console.log('生产日期开始:', this.queryParams.ProductionDateStart);
    }
    if (this.queryParams.ProductionDateEnd) {
      console.log('生产日期结束:', this.queryParams.ProductionDateEnd);
    }
    if (this.queryParams.ExpiryDateStart) {
      console.log('到期日期开始:', this.queryParams.ExpiryDateStart);
    }
    if (this.queryParams.ExpiryDateEnd) {
      console.log('到期日期结束:', this.queryParams.ExpiryDateEnd);
    }
    
    this.pageIndex = 1;
    this.loadData();
  }
  
  // 导出数据
  exportData(): void {
    alert('导出功能未实现');
  }
  
  // 刷新
  refresh(): void {
    this.loadData();
  }

  // 查看详情
  viewDetail(item: ChaKanGuanLianDto): void {
    console.log('查看详情:', item);
    
    // 导航到出入库流水页面，并传递商品信息作为查询参数
    this.router.navigate(['/stock/chu-ru-ku-liu-shui'], {
      queryParams: {
        goodsCode: item.goodsCode,
        goodsName: item.goodsName,
        batchNumber: item.batchNumber
      }
    });
  }

  // 处理生产日期变更
  onProductionDateChange(): void {
    console.log('生产日期变更:');
    console.log('- 开始日期:', this.queryParams.ProductionDateStart);
    console.log('- 结束日期:', this.queryParams.ProductionDateEnd);
  }
  
  // 处理到期日期变更
  onExpiryDateChange(): void {
    console.log('到期日期变更:');
    console.log('- 开始日期:', this.queryParams.ExpiryDateStart);
    console.log('- 结束日期:', this.queryParams.ExpiryDateEnd);
  }
  
  // 清空生产日期
  clearProductionDate(): void {
    this.queryParams.ProductionDateStart = '';
    this.queryParams.ProductionDateEnd = '';
    console.log('已清空生产日期');
  }
  
  // 清空到期日期
  clearExpiryDate(): void {
    this.queryParams.ExpiryDateStart = '';
    this.queryParams.ExpiryDateEnd = '';
    console.log('已清空到期日期');
  }
}